const { app, BrowserWindow, protocol, ipcMain, nativeTheme } = require('electron')
const { queryFile, savaEditConfig, savaData, getFileInfo } = require('./utils.cjs')
const path = require('path')
const configObj = require('./config.cjs')
// 编辑器配置
const editConfig = configObj
const createWindow = () => {
  console.log(console.log(configObj));
  const win = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.cjs')
    }
  })
  win.loadURL('http://localhost:3721/')
  win.webContents.openDevTools()

  // 切换编辑器暗黑、夜晚模式
  ipcMain.handle('dark-mode:toggle', () => {
    if (nativeTheme.shouldUseDarkColors) {
      nativeTheme.themeSource = 'light'
    } else {
      nativeTheme.themeSource = 'dark'
    }
    return nativeTheme.shouldUseDarkColors
  })
  ipcMain.handle('dark-mode:system', () => {
    nativeTheme.themeSource = 'system'
  })
  // 图片上传
  ipcMain.handle('uploader', (event, file) => queryFile(file, editConfig.fileSavePosition))
  // 保存config
  ipcMain.handle('changeConfig', (event, confiItem) => savaEditConfig(editConfig, confiItem))
  // 保存数据
  ipcMain.handle('savaData', (event, { path, data }) => savaData(path, data))
  // 获取文件数据
  ipcMain.handle('getFileInfo', (event, path) => getFileInfo(path))
}

app.whenReady().then(() => {
  // 渲染可以访问本地图片
  protocol.registerFileProtocol('myfile', (request, callback) => {
    const url = request.url.replace('myfile://', '');
    callback({ path: url });
  });
  createWindow()
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
  })
})